<?php

class Controller_Base extends Yaf_Controller_Abstract
{
    public static $AdminAssetsRole= [
        '28' => '4',
        '33' => '7',
    ];


    public function init()
    {
        // 解析URL
        $controller       = strtolower($this->getRequest()->getControllerName());
        $action           = strtolower($this->getRequest()->getActionName());
        $this->controller = $controller . 'Controller';
        $this->action     = $action . 'Action';
        $this->post_data  = $this->getRequest()->getPost();
        $this->admin = SmartyAdapter::getTplVars('admin');
        //通告
        $ts = time();
        $notice = Module_InfoBase_Notice::getInstance()->getOne([], ["status=1", "addTime<={$ts}", "endTime>{$ts}"], true);
        SmartyAdapter::assign('caseType',  Module_Mediate_Case::$caseType);
        SmartyAdapter::assign('notice', empty($notice['content'])?'':$notice['content']);
    }


    public function getMediationOrgan()
    {
        if(isset(self::$AdminAssetsRole[$this->admin['id']])) {
            return [];
        }
        if ($this->admin['dataType'] == 1) {
            //仅自己的数据
            $where =  ["id = {$this->admin['mediationOrganId']}"];
        }else{
            $where = $this->getWhere('',[],'id',0);
        }
        SmartyAdapter::assign('mediationOrgan',
            array_column(
                Module_InfoBase_MediationOrgan::getInstance()->getAllBySearch(
                    ['id','name'],
                    ["where" => $where],
                    true
                ),
                null,
                'id')
        );
    }
    public function getAssets()
    {
        if(isset(self::$AdminAssetsRole[$this->admin['id']])) {
            SmartyAdapter::assign('assets',
                array_column(
                    Module_InfoBase_Assets::getInstance()->getAllBySearch(
                        ['id','name'],
                        ['where'=>["id in (".self::$AdminAssetsRole[$this->admin['id']].")"]],
                        true
                    ),
                    null,
                    'id')
            );
        }else{
            $assets = Module_InfoBase_Assets::getInstance()->getAllBySearch(
                ['id','name','applyName'],
                [],
                true
            );
            foreach ($assets as &$val){
                $val['name'] = empty($val['applyName']) ? $val['name'] : $val['applyName'].'-'.$val['name'];
            }
            SmartyAdapter::assign('assets',
                array_column(
                    $assets,
                    null,
                    'id')
            );
        }

    }
    public function getMediator($status=0,$worker=0)
    {
        if(isset(self::$AdminAssetsRole[$this->admin['id']])) {
           return [];
        }
        $where = $this->getWhere('id',[],'mediationOrganId',0);

        if($status){
            array_push($where,"status=1");
        }
        if($worker){
            array_push($where,"(workerId>0 or workerId2>0)");
        }
        SmartyAdapter::assign('mediator',
            array_column(
                Module_User_Administrator::getInstance()->getAllBySearch(
                    ['id','name'],
                    [
                        'where'=>$where
                    ],
                    true
                ),
                null,
                'id')
        );
    }
    public function my_addslashes($str)
    {
        $str = str_replace(array("\r\n", "\r", "\n", " "), '', $str);
        return addslashes(stripcslashes($str));
    }


    /**
     * @param $where
     * 如果不是1平台的用户, 就查看 自己平台数据
     * 使用该方法 确保 表中有 mediationOrganId 字段
     */
    public function getWhere($pk='mediatorId',$where=[],$field = 'mediationOrganId',$search = 1){

        if(isset(self::$AdminAssetsRole[$this->admin['id']])){
            $controller = strtolower($this->getRequest()->getControllerName());
            if(in_array($controller,['caserecord','caseimport','callout','callin','returnedmoney','casecenter'])){
                array_push($where, "assetsId in (" . self::$AdminAssetsRole[$this->admin['id']].")");
            }elseif(in_array($controller,['export'])){
                array_push($where, "{$pk} = {$this->admin['id']}");
            }else{
                array_push($where, "1=0");
            }
            return $where;
        }
        if($this->admin['role_id'] == 1){
            if($search == 1){
                $mediationOrganId = trim($this->getRequest()->getQuery('mediationOrganId', 0));
                //能看全部组织数据
                if ($mediationOrganId) {
                    array_push($where, "{$field} = " . $mediationOrganId);
                }
            }

            return $where;
        }
        if ($this->admin['dataType'] == 1) {
            //仅自己的数据
            array_push($where, "{$pk} = {$this->admin['id']}");
        } elseif ($this->admin['dataType'] == 2) {
            //自己部门所有数据
            array_push($where, "{$field} = {$this->admin['mediationOrganId']}");
        }elseif ($this->admin['dataType'] == 3) {
            if($search == 1) {

                $mediationOrganId = trim($this->getRequest()->getQuery('mediationOrganId', 0));
                //能看全部组织数据
                if ($mediationOrganId) {
                    array_push($where, "{$field} = " . $mediationOrganId);
                }
            }
            return $where;
        }elseif ($this->admin['dataType'] == 4) {
            $mediationOrganId = trim($this->getRequest()->getQuery('mediationOrganId', 0));
            //能看全部组织数据
            if ($mediationOrganId && $search == 1) {
                array_push($where, "{$field} = " . $mediationOrganId);
            }else{
                array_push($where, "{$field} in ({$this->admin['allowOrganId']})");
            }
            return $where;
        }
        return $where;
    }

    /**
     * @param $where
     * 根据当事人名字查询案件id
     */
    protected function getCaseIdByLitigantName($litigantName){
        $res = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId'],['where'=>["litigantName = '{$litigantName}'"]]);
        if(empty($res)){
            return 0;
        }
        return implode(array_column($res,'caseId'),',');
    }
    /**
     * @param $where
     * 根据当事人信息查询案件id
     */
    protected function getCaseIdByLitigant($litigantVal,$type = 'litigantName'){
        if($type == 'litigantName'){
            $res = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId'],['where'=>["litigantName like '%{$litigantVal}%'"]]);
        }else{
            $res = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId'],['where'=>["{$type} = '{$litigantVal}'"]]);
        }
        if(empty($res)){
            return 0;
        }
        return implode(array_column($res,'caseId'),',');
    }

    /**
     * 基本数据校验
     */
    protected function checkParam()
    {
        foreach ($this->params as $param) {
            if (!isset($this->post_data) || empty($this->post_data[$param])) {
                $this->response_data = [
                    'code' => 4001,
                    'message' => Setup_Error::getConfig(4001),
                    'data' => []
                ];
                $this->getResponse()->setBody(json_encode($this->response_data));
                return false;
            }
        }
        return true;
    }

    /**
     * @param        $code
     * @param string $message
     * @param array  $data
     */
    protected function handleResponse( $code, $message="", $data = [] )
    {
        $this->response_data['code']    = isset($code) ? $code : 200;
        $this->response_data['message'] = !empty($message) ? $message : (isset($code) ? Setup_Error::getConfig($code) : "");
        $this->response_data['data']    = $data;
        $this->getResponse()->setBody(json_encode($this->response_data));
        $this->getResponse()->response();
        exit();
    }


    public function displayError($msg = '出错啦', $action = '', $title = '出错啦') {
        SmartyAdapter::assign('msg', $msg);
        SmartyAdapter::assign('action', $action);
        SmartyAdapter::assign('title', $title);
        SmartyAdapter::$templateName = 'error/error';
        SmartyAdapter::display();
        exit;
    }

    /**
     * 检测身份证号
     */
    public function checkCard($cardId) {
        if (!$cardId) {
            return false;
        }
        $regx= '#(^\d{15}$)|(^\d{17}(\d|x)$)|(^\d{17}(\d|X)$)#';
        $res = preg_match($regx, $cardId);
        return $res ? true : false;
    }

    /**
     * 检测 社会信用代码
     */
    public function checkUnifiedSocialCred($code) {
        if (!preg_match('~^[0-9ABCDEFGHJKLMNPQRTUWXY]{18}$~', $code)) {
            return false;
        }
        return true;
    }
    /**
     * 检测手机号
     */
    public function checkMobile($mobile) {
        if (!$mobile) {
            return false;
        }
        if(preg_match("/^1[3456789]\d{9}$/", $mobile)){
            return true;
        }
        return false;
    }

    //发送模板渲染
    public function getSMSConf($type){
        $sms_arr = [];
        if(isset(Lib_SMS_Config::$smsType[$type])){
            $sms_name = Lib_SMS_Config::$smsCode;
            $sms_template = Lib_SMS_Config::$smsContent;
            foreach (Lib_SMS_Config::$smsType[$type] as $k => $code){
                $sms_arr[$k]['code'] = $code;
                $sms_arr[$k]['name'] = $sms_name[$code];
                $sms_arr[$k]['content'] = $sms_template[$code];
            }
        }
        SmartyAdapter::assign('sms',$sms_arr);
    }


    public function Sec2Time($time){
        if(is_numeric($time)){
            $value = array(
                "hours" => '00',
                "minutes" => '00',
                "seconds" => '00',
            );
            if($time >= 3600){
                $value["hours"] = sprintf('%02d',floor($time/3600));
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = sprintf('%02d',floor($time/60));
                $time = ($time%60);
            }
            $value["seconds"] = sprintf('%02d',floor($time));
            //return (array) $value;
            $t=$value["hours"] .":". $value["minutes"] .":".$value["seconds"];
            Return $t;

        }else{
            return (bool) FALSE;
        }
    }
    /**
     * 返回Json数据
     * @param unknown $code
     * @param array|string|int|bool $data
     * @param string $message
     * @throws Exception
     */
    public function _returnJson($code,$data=array(),$message=''){
        $code = intval($code);
        if(empty($message)){
            $message = TyLib_Error::getMsg($code);
        }

        $returnData = array(
            'code'=>$code,
            'message'=>$message,
            'data'=>$data
        );
        header("Content-type: application/json");
        echo json_encode($returnData);
        exit;
    }

}
